package com.ruicar.afs.cloud.gateway.handler;

import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.security.feign.Oauth2OperationService;
import com.ruicar.afs.cloud.common.core.util.ClientTypeUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.gateway.util.AfsGateWayHelper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Fzero
 * @date 2019-01-24
 * 登录处理逻辑
 */
@Slf4j
@Component
@AllArgsConstructor
public class AfsRefreshTokenHandler extends AbstractOauthOperationHandler{
	private final Oauth2OperationService oauth2OperationService;

	/**
	 * Handle the given request.
	 *
	 * @param request the request to handle
	 * @return the response
	 */
	@Override
	public Mono<ServerResponse> handle(ServerRequest request) {
		Map<String, String> requestParam = new HashMap<>(8);
		requestParam.put(CommonConstants.GRANT_TYPE, "refresh_token");
		ClientTypeUtil.ClientTypeEnum clientTypeEnum =  AfsGateWayHelper.getClientType(request);
		requestParam.put("client_id", clientTypeEnum.getClientId());
		requestParam.put("client_secret", clientTypeEnum.getClientSecret());
		requestParam.putAll(request.queryParams().toSingleValueMap());
		Object object = oauth2OperationService.refresh(requestParam);
		return ServerResponse
				.status(HttpStatus.OK)
				.contentType(MediaType.APPLICATION_JSON)
				.body(BodyInserters.fromObject(new IResponse(object, "success")));
	}
}
